package com.neudu.ssrs_yyzxservice.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.neudu.ssrs_yyzxservice.common.JSONReturn;
import com.neudu.ssrs_yyzxservice.utils.FLAGS;
import com.neudu.ssrs_yyzxservice.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

public class UserInterceptor implements HandlerInterceptor {

    JSONReturn jsonReturn = new JSONReturn();

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler){
        //打印处理器方法名
        String wholePath = handler.toString();
        String methodName = wholePath.substring(wholePath.indexOf("#") + 1);

        System.out.print("==================处理器[");
        System.out.print(methodName);
        System.out.println("]==================");

        //验证token
        try {
            String token = req.getHeader(FLAGS.TOKEN);
            if(token == null || token.trim().length() == 0){
                System.out.println("没有获取到token");
                resp.getWriter().write(jsonReturn.returnError("未登录或登录超时，请重新登录！"));
                //不调用拦截器，直接返回
                return false;
            }

            //验证token加解密
            TokenUtil.authToken(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            jsonReturn.returnError(e.getMessage());
            return false;
        }
    }

}
